package com.github.cyf.task;

import com.github.cyf.common.util.MDCUtil;
import java.util.Map;

/**
 * 方式二：包装任务
 * @author chenyifan
 * @create 2024-09-03 14:27
 */
public class MdcRunnable implements Runnable {

    private Map<String, String> contextMap;
    private Runnable runnable;

    public MdcRunnable(Runnable runnable) {
        this.contextMap = MDCUtil.getCopyOfContextMap();
        this.runnable = runnable;
    }

    @Override
    public void run() {
        try {
            MDCUtil.setContextMap(contextMap);
            runnable.run();
        } finally {
            MDCUtil.clear();
        }
    }
}
